package com.readingtree.library.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

/**
 * Created by Administrator on 2017/4/18.
 */
public class JWTHelper {


    public static Claims parseJWT(String jsonWebToken, String secret) {
        if (secret != null && jsonWebToken !=null) {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(secret))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        }
        return null;
    }

    public static String createJWT(String username, Long userId, String roleName
            , String secret) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").setHeaderParam("alg", "HS512")
                .setSubject("lib").
                        claim("username", username).claim("userId", userId)
                .claim("roleName", roleName)
                .signWith(signatureAlgorithm, signingKey);
        //生成JWT
        return builder.compact();
    }

}
